package com.unohacha.qqj.fzdr;

import android.Manifest;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.huangmin66.rongcloud.RongCloudUtils;
import com.huangmin66.rongcloud.listener.MyConnectListener;
import com.igexin.sdk.PushManager;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.main.AddActivity;
import com.unohacha.qqj.fzdr.main.FindFragment;
import com.unohacha.qqj.fzdr.main.FirstPagerFragment;
import com.unohacha.qqj.fzdr.main.MessageFragment;
import com.unohacha.qqj.fzdr.personal.view.fragment.MyFragment;
import com.unohacha.qqj.fzdr.push.DemoIntentService;
import com.unohacha.qqj.fzdr.push.DemoPushService;
import com.unohacha.qqj.fzdr.util.CommonUtils;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.mylibrary.base.BaseActivity;
import com.unohacha.qqj.mylibrary.base.BaseFragment;
import com.unohacha.qqj.mylibrary.listener.PermissionListener;
import com.unohacha.qqj.mylibrary.view.TabPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import butterknife.OnClick;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;
import rx.Observable;
import rx.functions.Action1;

/**
 * 主入口
 */
public class MainActivity extends BaseActivity {

    @BindView(R.id.main_tab_pager)
    TabPager mainTabPager;
    @BindView(R.id.main_first)
    TextView mainFirst;
    @BindView(R.id.main_message)
    TextView mainMessage;
    @BindView(R.id.main_add)
    ImageView mainAdd;
    @BindView(R.id.main_find)
    TextView mainFind;
    @BindView(R.id.main_my)
    TextView mainMy;

    @BindView(R.id.iv1)
    ImageView iv_home;
    @BindView(R.id.iv2)
    ImageView iv_message;
    @BindView(R.id.iv3)
    ImageView iv_find;
    @BindView(R.id.iv4)
    ImageView iv_wode;

    @BindView(R.id.rl1)
    RelativeLayout rl_home;
    @BindView(R.id.rl2)
    RelativeLayout rl_message;
    @BindView(R.id.rl3)
    RelativeLayout rl_find;
    @BindView(R.id.rl4)
    RelativeLayout rl_wode;
    private List<BaseFragment> frgs = new ArrayList<>();

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    public AMapLocationClient mLocationClient = null;
    private double longitude;
    private double latitude;
    private String adaddress;
    public Handler mHandler;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        super.initView();
        //初始按钮
        mainFirst.setTextColor(MainActivity.this.getResources().getColor(R.color.black));
        iv_home.setBackgroundResource(R.drawable.home1);
        initFragments();
        String[] names = {"要打印的字符串1", "2"};
        Observable.from(names).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {

            }
        });
        initMap();
        initLocation();
        PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if( Prefer.getInstance().getToken()==null ||  Prefer.getInstance().getToken().equals("")){
            return;
        }

        final String uid=Prefer.getInstance().getUser_id();
        final String uName=Prefer.getInstance().getName();
        final String chatid=Prefer.getInstance().getChatid();
        Log.e("TAG: 头像:",Prefer.getInstance().getImage());
        RongCloudUtils.getInstance()
                .connect(this,chatid, new MyConnectListener(){
                    @Override
                    public void onSuccess(String userid) {
                        super.onSuccess(userid);
                        Log.e("TAG: connect","连接成功");
                        RongCloudUtils.getInstance()
                                .setCurrentUserInfo(new UserInfo(uid, uName, Uri.parse(Prefer.getInstance().getImage())));
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                        super.onError(errorCode);
                        Log.e("TAG: onError: ",errorCode.getMessage());
                    }
                });
    }

    private void initMap() {
        mHandler = new Handler();
        mHandler.post(runnableLocation);
    }

    Runnable runnableLocation = new Runnable() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void run() {
            //动态注册权限
            if (23 <= CommonUtils.getSDKVersion()) {
                requestRunPermisssion(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, new PermissionListener() {
                    @Override
                    public void onGranted() {
                        //启动定位
                        mLocationClient.startLocation();
                    }

                    @Override
                    public void onDenied(List<String> deniedPermission) {
                        MyToast(getResources().getString(R.string.permission_location));
                    }
                });
            } else {
                //启动定位
                mLocationClient.startLocation();
            }
        }
    };

    private void initFragments() {
        frgs.add(new FirstPagerFragment());
        frgs.add(new MessageFragment());
        frgs.add(new FindFragment());
        frgs.add(new MyFragment());
        mainTabPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return frgs.get(position);
            }

            @Override
            public int getCount() {
                return frgs.size();
            }

            @Override
            public void unregisterDataSetObserver(@NonNull DataSetObserver observer) {
                if (observer != null) {
                    super.unregisterDataSetObserver(observer);
                }
            }
        });
    }

    @OnClick({R.id.rl1, R.id.rl2, R.id.main_add, R.id.rl3, R.id.rl4})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl1:
                mainTabPager.setCurrentItem(0);
                //改变背景颜色及字体
                mainFirst.setTextColor(MainActivity.this.getResources().getColor(R.color.black));
                iv_home.setBackgroundResource(R.drawable.home1);
                //重置其他按钮
                mainMessage.setTextColor(MainActivity.this.getResources().getColor(R.color.text_black_999));
                iv_message.setBackgroundResource(R.drawable.xiaoxi);

                mainFind.setTextColor(MainActivity.this.getResources().getColor(R.color.text_black_999));
//                iv_find.setBackgroundResource(R.drawable.add);
                iv_find.setBackgroundResource(R.drawable.ic_find_normal);

                mainMy.setTextColor(MainActivity.this.getResources().getColor(R.color.text_black_999));
                iv_wode.setBackgroundResource(R.drawable.wd);

                break;
            case R.id.rl2:
                mainTabPager.setCurrentItem(1);
                //改变背景颜色及字体
                mainFirst.setTextColor(MainActivity.this.getResources().getColor(R.color.text_black_999));
                iv_home.setBackgroundResource(R.drawable.home);
                //重置其他按钮
                mainMessage.setTextColor(MainActivity.this.getResources().getColor(R.color.black));
                iv_message.setBackgroundResource(R.drawable.xiaoxi2);

                mainFind.setTextColor(MainActivity.this.getResources().getColor(R.color.text_black_999));
                // mainFind.setBackgroundResource(R.drawable.add);
                iv_find.setBackgroundResource(R.drawable.ic_find_normal);
                mainMy.setTextColor(MainActivity.this.getResources().getColor(R.color.text_black_999));
                iv_wode.setBackgroundResource(R.drawable.wd);

                break;
            case R.id.main_add:
                jumpToOtherActivity(this, AddActivity.class);
                break;
            case R.id.rl3:
                mainTabPager.setCurrentItem(2);
                //改变背景颜色及字体
                mainFirst.setTextColor(MainActivity.this.getResources().getColor(R.color.text_black_999));
                iv_home.setBackgroundResource(R.drawable.home);
                //重置其他按钮
                mainMessage.setTextColor(MainActivity.this.getResources().getColor(R.color.text_black_999));
                iv_message.setBackgroundResource(R.drawable.xiaoxi);

                mainFind.setTextColor(MainActivity.this.getResources().getColor(R.color.black));
//                mainFind.setBackgroundResource(R.drawable.ic_find);
                iv_find.setBackgroundResource(R.drawable.ic_find);

                mainMy.setTextColor(MainActivity.this.getResources().getColor(R.color.text_black_999));
                iv_wode.setBackgroundResource(R.drawable.wd);
                break;
            case R.id.rl4:
                mainTabPager.setCurrentItem(3);
                //改变背景颜色及字体
                mainFirst.setTextColor(MainActivity.this.getResources().getColor(R.color.text_black_999));
                iv_home.setBackgroundResource(R.drawable.home);
                //重置其他按钮
                mainMessage.setTextColor(MainActivity.this.getResources().getColor(R.color.text_black_999));
                iv_message.setBackgroundResource(R.drawable.xiaoxi);

                mainFind.setTextColor(MainActivity.this.getResources().getColor(R.color.text_black_999));
                // mainFind.setBackgroundResource(R.drawable.add);
                iv_find.setBackgroundResource(R.drawable.ic_find_normal);
                mainMy.setTextColor(MainActivity.this.getResources().getColor(R.color.black));
                iv_wode.setBackgroundResource(R.drawable.wd2);
                break;
        }
    }


    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        mLocationClient = new AMapLocationClient(MainActivity.this);
        mLocationOption = getDefaultOption();
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        // 设置定位监听
        mLocationClient.setLocationListener(mAMapLocationListener);
        mLocationOption.setOnceLocationLatest(true);
    }

    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    //获取定位结果
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (null != aMapLocation) {
                if (aMapLocation.getErrorCode() == 0) {
                    //经度
                    longitude = aMapLocation.getLongitude();
                    //纬度
                    latitude = aMapLocation.getLatitude();
                    String province = aMapLocation.getProvince();//省
                    String city = aMapLocation.getCity();
                    String district = aMapLocation.getDistrict();
                    //地址
                    adaddress = aMapLocation.getAddress();

                    Prefer.getInstance().saveProRegion(MainActivity.this, district);
                    Prefer.getInstance().saveProCity(MainActivity.this, province + "," + city);
                    Prefer.getInstance().saveLocation(MainActivity.this, latitude + "," + longitude);

                } else {
                    int errorCode = aMapLocation.getErrorCode();//错误码
                    String errorInfo = aMapLocation.getErrorInfo() + aMapLocation.getLocationDetail();//错误信息

                }
            } else {
                MyToast("获取当前位置失败!");
            }
        }
    };


    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                MyToast("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                MyApplication.getInstance().exit(this);
                finish();
            }

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
